<template>
    <div style="background-color: #fff; padding: 24px;">
		
		<div style="margin-bottom: 24px;">
			<el-button type="primary" size="small" icon="PlusIcon" @click="onAddItem">添加</el-button>
			<el-button 
				:type="'success'" size="small" plain
				@click="handlerAllSetbutton('1')">
					启用 
			</el-button>

			<el-button 
				:type="'warning'" size="small" plain
				@click="handlerAllSetbutton('2')">
					禁用
			</el-button>

			
				<div style="display: flex; display: inline-block;margin-left: 18px; ">
					<el-select 	
					filterable allow-create
					v-model="form.tags" placeholder="分类查询" @change="selectTags" style="width: 200px;">
						<el-option v-for="(item,index) in tagsList " :key="index" :label="item.goods_tags_name" :value="item.id"></el-option>
					</el-select>
				</div>

		</div>

		<el-table :scrollbar-always-on="true" ref="tableRef" @selection-change="handleSelectionChange" 
		@row-click="handleClickRow"
		:header-cell-style="{
                        background: '#F5F5F5',
                        color: '#606266',
                        height: '46px'
                    }" size="small" wdith="100%" border :data="tableData">
					<el-table-column type="selection" width="45" fixed="left"  />
					<el-table-column align="center" label="商品名" prop="goods_name" width="200" show-overflow-tooltip />
					<el-table-column align="center" label="商品信息" prop="content"  show-overflow-tooltip/>

					<el-table-column align="center" label="时间" prop="created_at" width="160px" />
					<el-table-column align="center" label="分类" prop="goods_tags_name" width="160px" >
					<template #default="scope">
						<el-tag>{{ scope.row.goods_tags_name }}</el-tag>
						</template>
					</el-table-column>
					<!-- <el-table-column align="center" label="时间" prop="goods" width="160px" /> -->
					<el-table-column align="center" label="图片地址" prop="img_url" width="130px" >
					<template #default="scope">
						<img  style="width: 50px; height: 50px;" class="logo-img" :src="scope.row.img_url" /> 
						</template>
					</el-table-column>

					<el-table-column align="center" label="状态"   width="130px" >
						<template #default="scope">
							<el-switch v-model="scope.row.status"   @change="handlerStatus(scope.row)" active-color="#13ce66" inactive-color="#ff4949">
							</el-switch>
						</template>
					</el-table-column>

					<el-table-column align="center" label="副图片" prop="content" >
						<template #default="scope">
							<!-- Modify scrollbar style -->
							<div style="" class="image_subplot">
								<div v-for="(item,index) in scope.row.goods_images" :key="index">
									<img style="width: 50px; height: 50px; margin-right: 10px;" class="logo-img" :src="item.subplot_img_url" />
								</div>
							</div>
						</template>
					</el-table-column>

					<el-table-column align="center" label="状态" width="150">
						<template #default="scope">
							<el-tag size="small" :type="scope.row.status ? 'success' : 'danger'">
								{{ scope.row.status ? '正常' : '禁用' }}
							</el-tag>
						</template>
					</el-table-column>
					
					<el-table-column align="center" label="操作" fixed="right" width="200" >
						<template #default="scope">
							<el-button v-if="scope.row.username != 'adminWork'" type="primary" size="small" plain
								@click="onEditItem(scope.row)">编辑</el-button>
							<!-- <el-button v-if="scope.row.username != 'adminWork'"  type="danger" size="small" plain @click="onDeleteItem(scope.row)">删除</el-button> -->
							<!-- <el-button v-if="scope.row.username != 'adminWork'"
								:type="scope.row.status === 1 ? 'warning' : 'success'" size="small" plain
								@click="onEnableItem(scope.row)">
								{{ scope.row.status === 1 ? '禁用' : '启用' }}
							</el-button> -->
						</template>
					</el-table-column>
		</el-table>

			<div class="demo-pagination-block" style="margin: 24px; display: flex;justify-content: center;">
				<el-pagination
					v-model:current-page="page"
					v-model:page-size="pageSize"
					layout="prev, pager, next, jumper"
					:total="total"
					@size-change="handleSizeChange"
					@current-change="handleCurrentChange"
				/>
			</div>

		<el-drawer title="添加或者编辑" v-model="drawer" :with-header="false">
			<span>添加商品</span>

			<div style="width: 100%; margin-top:24px">
				<el-form  :model="form" label-width="80px">
					<el-form-item label="商品名">
						<el-input v-model="form.goods_name"></el-input>
					</el-form-item>

					<el-form-item label="商品信息">
					<textarea v-model="form.goods_info" name="" id="" cols="30" rows="10" style="width: 100%;"></textarea>

						<!-- <el-input v-model="form.goods_info"></el-input> -->
					</el-form-item>

					<el-form-item label="分类" label-width="80px" >
						<el-select v-model="tagsVal" placeholder="分类查询" @change="gethandlerTags" style="width: 200px;">
							<el-option v-for="(item,index) in tagsList " :key="index" :label="item.goods_tags_name" :value="item.id"></el-option>
						</el-select>
					</el-form-item>

					<!-- <el-form-item label="选择">
						<el-select v-model="form.region" placeholder="请选择活动区域">
						<el-option label="区域一" value="shanghai"></el-option>
						<el-option label="区域二" value="beijing"></el-option>
						</el-select>
					</el-form-item> -->
					<!-- 
					<el-form-item label="主图">
						<el-col :span="11">
						<el-date-picker
							type="date"
							placeholder="选择日期"
							v-model="form.date1"
							style="width: 100%;"
						></el-date-picker>
						</el-col>
						<el-col class="line" :span="2">-</el-col>
						<el-col :span="11">
						<el-time-picker
							placeholder="选择时间"
							v-model="form.date2"
							style="width: 100%;"
						></el-time-picker>
						</el-col>
					</el-form-item> -->


					<el-form-item label="状态">
						<el-switch v-model="form.delivery" />
					</el-form-item>
		
					<el-form-item label="主图">
							<el-upload
							class="avatar-uploader"
							:action="uploadIp"
							:show-file-list="false"
							:on-success="handleAvatarSuccess"
							:before-upload="beforeAvatarUpload"
							:headers="{
								token: Cookies.get(USER_TOKEN_KEY) || ''
							}"
							>
						
						<img v-if="imageUrl" :src="imageUrl"  class="avatar" />
						<el-icon style=" border: 1px dashed #999;" v-else class="avatar-uploader-icon"><Plus /></el-icon>
						</el-upload>
						
					</el-form-item>

					<el-form-item label="副图">
						<el-upload   v-model:file-list="fileList"  multiple :action="uploadIp"  :headers="{
								token: Cookies.get(USER_TOKEN_KEY) || ''
							}" list-type="picture-card"  
    						:on-remove="handleRemove"
							>  
							<el-icon><Plus /></el-icon>

							<!-- <template #file="{ file }">
							<div>
								<img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
								<span class="el-upload-list__item-actions">
								<span
									class="el-upload-list__item-preview"
									@click="handlePictureCardPreview(file)"
								>
									<el-icon><zoom-in /></el-icon>
								</span>
								<span
									v-if="!disabled"
									class="el-upload-list__item-delete"
									@click="handleDownload(file)"
								>
									<el-icon><Download /></el-icon>
								</span>
								<span
									v-if="!disabled"
									class="el-upload-list__item-delete"
									@click="handleRemove(file)"
								>
									<el-icon><Delete /></el-icon>
								</span>
								</span>
							</div>
							</template> -->
						</el-upload>

						<!-- <el-dialog v-model="dialogVisible">
							<img w-full :src="dialogImageUrl" alt="Preview Image" />
						</el-dialog> -->
											
					</el-form-item>

					<el-form-item>
						<el-button type="primary" @click="onSubmit">立即添加</el-button>
						<el-button>取消</el-button>
					</el-form-item>
					</el-form>

			</div>
		</el-drawer>


    </div>
</template>

<script lang="ts" setup>
import { nextTick, onMounted, reactive, ref ,watch} from 'vue'

import { post } from '@/api/http'
import { gethomeIndex  , editStatus ,addHomeIndex , updateHomeIndex ,getGoodsTags } from '@/api/url'
import { ElMessage, ElMessageBox } from "element-plus";
import { baseIp } from '@/api/axios.config'
import { USER_TOKEN_KEY } from '@/store/keys'
import Cookies from 'js-cookie'
import type { UploadFile } from 'element-plus'
import { result } from 'lodash';

const uploadIp = ref<String>(baseIp + '/InterviewTable/upload')

// const uploadSelect = ref<String>(baseIp + '/Home/HomeUpload')



const tableData = ref([  {
    date: '2016-05-03',
    name: 'Tom',
    state: 'California',
    city: 'Los Angeles',
    address: 'No. 189, Grove St, Los Angeles',
    zip: 'CA 90036',
    tag: 'Home',
  },] as any)


  const form  = reactive({
    goods_info: '',
    goods_name: '',
    delivery: false,
	tags:''
 }as any)

 const tagsList = ref<any>([]);
const  imageUrl = ref('')

const tagsVal = ref('')



// watch(() => form.tags, (newValue) => {
//       if (newValue && !tagsList.value.find((item:any) => item.goods_tags_id === newValue)) {
//         // 如果新值不存在于列表中，则添加
//         // const newTag = {
//         //   goods_tags_id: newValue, // 假设ID和名字相同
//         //   goods_tags_name: newValue
//         // };
//         // tagsList.value.push(newTag);
// 		post({
// 			url:addTags,
// 			data:{
// 				goods_tags_name: newValue
// 			}
// 		}).then((result:any)=>{
// 			handlerTags()
// 		})
//       }
//     });

const handleDownload = (file: UploadFile) => {
  console.log(file)
}
const total = ref<number>(0)

const drawer = ref<boolean>(false)

const  drawerId = ref(0)


const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const disabled = ref(false)
const  fileList = ref([])

const handleRemove = (file: UploadFile) => {
  console.log(file)
}


const  onEditItem = (val:any)=>{
	imageUrl.value = val.img_url
	form.delivery = val.status
	drawer.value = true
	form.goods_name = val.goods_name
	form.goods_info = val.content
	tagsVal.value = val.tags

	drawerId.value = val.id 
	console.log(val  , 'drawer')
	fileList.value = val.goods_images?.map((item:any)=>{
		return {
			name:item.subplot_img_url,
			url:item.subplot_img_url,
			status: 'done',
		}
	})
	console.log( val.goods_images  , 'fileList.valuefileList.value')
	console.log( fileList.value  , '321312')

}

//选择分类查询

const selectTags =async (val:any)=>{
	console.log(val  , 'valvalvalval')
	val == 0  ? form.tags = '' : form.tags = val
	gethomeData()
}


const  handleClickRow = (row:any)=>{
	console.log(allSelect.value ,'111111111')
}

//点击获取分类
const  handlerTags = async()=>{
	const reuslt = await post({
		url:getGoodsTags,
		data:{}
	})	
	tagsList.value = reuslt.data
	tagsList.value = tagsList.value
	const hasAllTag = tagsList.value.some((item:any)=> item.goods_tags_name === "全部");
	if (!hasAllTag) {
		tagsList.value.unshift({ goods_tags_name: "全部" ,goods_tags_id:0,id:0});
	}
}

const gethandlerTags  = (val:any )=>{
	tagsVal.value = val
}


const handleCreate  = (val:any)=>{

	console.log(val )

}


//提交
const  onSubmit =async ()=>{
	let result 
	if(!tagsVal.value || !form.goods_name || !form.goods_info || !imageUrl.value) return   ElMessage( '请正确填写')
	if(drawerId.value  == 0 ){
		let fineArray =  fileList.value.map((item:any)=>{
			return  item.response.url
		})

		let obj = {
			fineArray,
			goods_info:form.goods_info,
			goods_name: form.goods_name,
			delivery:form.delivery,
			imageUrl:imageUrl.value,
			tags:(tagsVal.value ) as string
		} as any
		console.log(typeof tagsVal.value  , '1111111111')
		console.log(obj   , 'obj')
		result = await post({
			url:addHomeIndex,
			data:obj
		})
	}else{

		let fineArray = fileList.value.map((item:any) => {
			if (item && item.response && item.response.url) {
				return item.response.url;
			} else {

				return item.url; // 或者其他处理方式，如返回默认值
			}
		});

		let obj = {
			id:drawerId.value,
			fineArray,
			goods_info:form.goods_info,
			goods_name: form.goods_name,
			delivery:form.delivery,
			imageUrl:imageUrl.value,
			tags:(tagsVal.value ) as string
		}

		result  = await post({
			url:updateHomeIndex,
			data:obj
		})
	}


	ElMessage(`${result.msg}`)
	drawer.value = false
	gethomeData()
}

const handleAvatarSuccess = (res:any, file:any)=> {
   	nextTick(() => {
		imageUrl.value = res.url
    });
}
const beforeAvatarUpload = (file:any) => {
  const allowedFormats = ['image/jpeg', 'image/png', 'image/gif']; // 允许的格式数组
  const isAllowedFormat = allowedFormats.includes(file.type); // 检查文件类型是否在允许的格式数组中
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isAllowedFormat) {
    ElMessage.error('上传头像图片只能是 JPG、PNG 或 GIF 格式!');
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!');
  }
  return isAllowedFormat && isLt2M;
};



//状态
const handlerAllSetbutton =async (title:string)=>{
	
	const  id =	allSelect.value.map((item:any)=>{
				return item.id
		})

	let  status
	title === '1' ?  status = 1 : status = 0
	const reuslt = await post({
		url:editStatus,
		data:{id, status,}
	})
	gethomeData()
	console.log(reuslt,'allSelect')
}

const  onAddItem = ()=>{
	drawer.value = true
	fileList.value = []
	imageUrl.value = ''
	    
    // 清空表单
    form.goods_info = ''
    form.goods_name = ''
	tagsVal.value = ''
    form.delivery = false

}




//全选
const allSelect = ref<any>([])
const handleSelectionChange = (val:any)=> {
        allSelect.value = val
}

const handleClick = () => {
  console.log('click')
}


const handlerStatus = async (val:any)=>{
	let status = val.status ? 1 : 0
	let id  = [val.id]
	const result = await post({
		url:editStatus,
		data:{id, status,}
	})


}

const page = ref(1)
const pageSize = ref(10)

const handleSizeChange = (val: number) => {
	pageSize.value = val 
	gethomeData()
}
const handleCurrentChange = (val: number) => {
	page.value = val 
	gethomeData()
}
const gethomeData = async ()=>{
    const result = await post({
      url:gethomeIndex,
	  data:{
		page:page.value,
		pageSize:pageSize.value,
		tags:form.tags
	  }
    })

	tableData.value =  result.data.data
	total.value = result.data.total
    console.log(result , 'resuilt')

}

onMounted(()=>{
  gethomeData()
  handlerTags()
})


</script>


<style scoped>
:deep .el-table--small .cell{
	padding: 8px 15px;
}

.image_subplot{
    display: flex;
    overflow-x: auto;
    scrollbar-width: thin; 
    scrollbar-color: #888 #f5f5f5; 
}

.image_subplot::-webkit-scrollbar {
    height: 5px;
}

.image_subplot::-webkit-scrollbar-track {
    background: #f5f5f5;
}

.image_subplot::-webkit-scrollbar-thumb {
    background: #888;
}


.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

</style>